<template>
  <div
    class="girl"
    :style="positionstyle"
    :id="'girl_' + name"
    draggable="false"
  >
    <div>{{ girl.name }}</div>
    <div>{{ girl.score }}</div>
    <img :src="img" width="100" height="100" draggable="false" />
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
import { randomInt } from "../common/Calculate";
import { Girl } from "../entities/Girl";

@Component
export default class Beauty extends Vue {
  @Prop() private name!: string;
  @Prop() private score!: number;
  @Prop() private img!: number;
  @Prop() private girl!: Girl;
  private x: number | any = 0;
  private y: number | any = 0;
  private positionstyle: string | any = null;
  private ele: HTMLElement | any;
  private pushDown: boolean = false;

  public created() {
    // console.log("created", this.name);
    console.log("创建", this.girl);
  }
  private generatePosition(nx: number, ny: number): void {
    this.x = nx;
    this.y = ny;
    this.positionstyle = {
      left: nx + "px",
      top: ny + "px",
    };
  }
  private resetPosition(nx: number, ny: number): void {
    // nx -= 20;
    // ny -= 120;
    let offsetX = nx - this.x;
    let offsetY = ny - this.y;
    offsetX = this.flatten(offsetX);
    offsetY = this.flatten(offsetY);
    this.x = nx;
    this.y = ny;

    let viewX = this.ele.style.left.split("px")[0];
    let viewY = this.ele.style.top.split("px")[0];

    this.ele.style.left = parseInt(viewX) + offsetX + "px";
    this.ele.style.top = parseInt(viewY) + offsetY + "px";

    // this.ele.style.left = parseInt(viewX) + offsetX + "px";
    // this.ele.style.top = parseInt(viewY) + offsetY + "px";

    // this.ele.style.left = this.x + "px";
    // this.ele.style.top = this.y + "px";
  }

  private flatten(val: number): number {
    const MAX_OFFSET = 5;
    if (val > MAX_OFFSET) {
      val = MAX_OFFSET;
    } else if (val < -MAX_OFFSET) {
      val = -MAX_OFFSET;
    }
    return val;
  }

  public mounted() {
    this.ele = document.getElementById("girl_" + this.name);
    this.ele.onmouseup = () => {
      this.pushDown = false;
      this.checkInPalace();
    };
    this.ele.onmouseout = () => {
      this.pushDown = false;
      // this.checkInPalace();
    };
    this.ele.onmousedown = (e: any) => {
      this.pushDown = true;
    };
    this.ele.onmousemove = (e: any) => {
      if (this.pushDown) {
        let x = e.screenX;
        let y = e.screenY;
        this.resetPosition(x, y);
      }
    };
    this.generatePosition(randomInt(200, 1500), randomInt(500, 700));
    // this.generatePosition(500, 350);
  }

  public checkInPalace() {
    if (this.y < 500) {
      this.$emit(
        "gotoPalace",
        this.girl,
        this.ele.style.left,
        this.ele.style.top
      );
    }
  }
}
</script>

<style>
</style>